package com.huanglejing.shanggou.rx


import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.common.AppContext
import com.huanglejing.shanggou.exception.APIException
import com.huanglejing.shanggou.utils.ToastUtils
import retrofit2.adapter.rxjava.HttpException
import rx.Subscriber
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.*

/**
 * Created by Administrator on 2016/7/21 0021.
 */
open class SimpleSubscriber<T> : Subscriber<T>() {

    private val TAG: String = this.javaClass.name

    override fun onStart() {
        super.onStart()
        KLog.i(TAG, ": onStart >>")
    }


    override fun onCompleted() {
        unsubscribe()
        KLog.i(TAG, "onCompleted >> ")
    }

    override fun onError(e: Throwable) {
        e.printStackTrace()
        var code = -1
        if (e is APIException) {
            code = e.code
            KLog.e(TAG, "error code : $code ; msg = ${e.message}")
        }

        when (e) {
            is HttpException -> {
                code = e.code()
                KLog.d("HttpException : code = $code")
                if (code == 504) {
                    ToastUtils.toastLong(AppContext.get().resources.getString(R.string.str_no_net))
                    return
                }
            }
            is SocketException -> {
                ToastUtils.toastLong(AppContext.get().resources.getString(R.string.str_no_response))
                return
            }
            is SocketTimeoutException -> {
                ToastUtils.toastLong(AppContext.get().resources.getString(R.string.str_time_out))
                return
            }
            is UnknownHostException -> {
                ToastUtils.toastLong(AppContext.get().resources.getString(R.string.str_host_error))
                return
            }
            is NoSuchElementException -> {
                if (e.message == "Sequence contains no elements") {
                    ToastUtils.toastLong(AppContext.get().resources.getString(R.string.str_no_data))
                    return
                }
            }
            else -> {
                e.message?.trim()?.let {
                    ToastUtils.toastLong(it)
                }
            }
        }
        KLog.e(TAG, "$TAG: onError >> code = $code + info : ${e.message}")
    }

    override fun onNext(t: T) {
        KLog.i(TAG, "t = $t")
    }
}
